from collections import defaultdict
from openpyxl import Workbook
import datetime
import random
import time
import requests
import os

def send_request(url_key, header_key, urls_dict, headers_dict):
    url = urls_dict[url_key]
    headers = headers_dict[header_key].copy()
    headers["X-Timestamp"] = str(int(time.time()))

    try:
        # 设置超时时间为20秒
        response = requests.get(url, headers=headers, timeout=20)
        return response
    except requests.exceptions.Timeout:
        # 请求超时处理
        print(f"请求 {url_key} 超时, 从消费方 {header_key} 发出.")
    except Exception as e:
        # 其他错误处理
        print(f"请求 {url_key} 时出错：{e}")
    # 返回None以表示请求未成功
    return None

def create_output_directory(output_dir):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

# 设定URL和请求头的字典
urls_dict = {
    "买西瓜看那里": "http://10.10.2.236:32287/double12/getPriceWaterM",
    "买大米看这里": "http://10.10.2.236:32287/double12/getPriceRice",
    "买手机看那里": "http://10.10.2.236:32287/double11/getPriceMoblie",
    "买电脑看这里": "http://10.10.2.236:32287/double11/getPriceCOM"
}

headers_dict = {
    "马斯克": {"Content-Type": "application/json","X-Signature": "1","X-App-Id": "G3sDUhdt","X-Timestamp": "1","X-Sequence-No": "1"},
    "宝马用户": {"Content-Type": "application/json","X-Signature": "1","X-App-Id": "YXByRhUg","X-Timestamp": "1","X-Sequence-No": "1"},
    "比尔盖茨": {"Content-Type": "application/json","X-Signature": "1","X-App-Id": "EI22HfB9","X-Timestamp": "1","X-Sequence-No": "1"}
}

# 初始化Excel工作簿并设置列名称
wb = Workbook()
ws = wb.active
ws.title = "计价账单"
ws.append(["接口", "消费方", "调用次数", "最近调用时间"])

# 获取脚本持续时间
script_duration_minutes = int(input("请输入脚本持续时间（分钟）: "))

# 初始化用于记录请求信息的字典
request_counts = defaultdict(int)

# 确保输出目录存在
output_directory = "filesOutput"
create_output_directory(output_directory)

# 开始发送请求
start_time = datetime.datetime.now()
end_time = start_time + datetime.timedelta(minutes=script_duration_minutes)

while datetime.datetime.now() < end_time:
    for _ in range(3):
        url_key = random.choice(list(urls_dict.keys()))
        header_key = random.choice(list(headers_dict.keys()))

        response = send_request(url_key, header_key, urls_dict, headers_dict)
        if response:
            request_key = (url_key, header_key)
            if 200 <= response.status_code <= 399:  # 成功的响应
                request_counts[request_key] += 1
                print(f"请求接口 {url_key} 成功, 消费方为 {header_key}. 目前已调用次数：{request_counts[request_key]}")
            else:  # 错误的响应
                print(f"请求接口 {url_key} 失败，响应码为 {response.status_code}, 消费方为 {header_key}.")

    time.sleep(10)

# 写入数据到Excel
for request_key, count in request_counts.items():
    url_key, header_key = request_key
    ws.append([url_key, header_key, count, datetime.datetime.now().isoformat()])

# 保存Excel文件
file_name = "统计分析-计费统计.xlsx"
file_path = os.path.join(output_directory, file_name)
wb.save(file_path)
print(f"Excel文件已保存至: {file_path}")